package top.xxyu.web.login;

import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.weibo.UserInfo;
import com.qq.connect.javabeans.weibo.UserInfoBean;
import com.qq.connect.oauth.Oauth;
import lombok.extern.java.Log;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@Log
public class QQLoginController {

    /**
     * QQ登录跳转
     * @throws QQConnectException
     * @throws IOException
     */
    @RequestMapping(value="QQUserLogin")
    public void qqLogin(HttpServletRequest req, HttpServletResponse resp, HttpSession session) throws IOException, QQConnectException {
        try {
            String url = new Oauth().getAuthorizeURL(req);
            resp.sendRedirect(url);
            session.setAttribute("beforLoginUrl","/");
        } catch (Exception e) {
            new QQConnectException("跳转到QQ登录页面异常");
        }
    }

    /**
     * QQ登录回调
     * @param req
     * @param resp
     * @param session
     * @return
     * @throws QQConnectException
     */
    @RequestMapping(value="/connect/callback/qq")
    public String qqcallback(HttpServletRequest req,HttpServletResponse resp,HttpSession session) throws QQConnectException{
        resp.setContentType("text/html;charset=utf-8");
        int  bindTag =  0;
        try {
            String code = req.getParameter("code");
            String state = req.getParameter("state");
            String  session_state= (String) session.getAttribute("qq_connect_state");
            if(StringUtils.isNotBlank(session_state) && session_state.equals(state)){
               /* String accessToken = QQLoginUT.getAccessToken(code);
                session.setAttribute("accessToken", accessToken);
                if (StringUtils.isBlank(accessToken)) {
                    log.error("没有获取到响应参数");
                }else{
                    OpenID openIDObj =  new OpenID(accessToken);
                    String openID = openIDObj.getUserOpenID();
                    UserInfo qzoneUserInfo = new UserInfo(accessToken, openID);
                    UserInfoBean userInfoBean = qzoneUserInfo.getUserInfo();
                    if(userInfoBean != null && userInfoBean.getRet() == 0 && StringUtils.isBlank(userInfoBean.getMsg())){
                        //获取用户成功
                        User user = (User) commonService.getObject("from User where open_id = ? ", new Object[]{openID});
                        if(null != user){
                            //判断用户邮箱是为为空，主要是针对最早期的用户，有邮箱未完善的
                            //已经注册过，更新用户信息，直接将信息存入session 然后跳转
                            user.setUser_name(userInfoBean.getNickname());
                            user.setUser_pic(userInfoBean.getAvatar().getAvatarURL100());
                            user.setGender(userInfoBean.getGender());
                            user.setFirst_ip(TimeHelper.getCurrentTime());
                            if(commonService.updateObject(user) < 1){
                                throw new Exception("更新用户信息错误");
                            }
                            if(StringUtils.isNotBlank(user.getEmail())){
                                bindTag = 1;//邮箱不为空，正常跳转到首页
                            }else{
                                bindTag = 2;//邮箱为空跳转到绑定页面
                            }
                        }else{
                            //该用户第一次登录 先注册
                            user = new User();
                            user.setOpen_id(openID);
                            user.setUser_name(userInfoBean.getNickname());
                            user.setRealm((Realm)commonService.getObject(Realm.class, "b18caeea1ec378e689263cee8d8c8123"));
                            user.setUser_pic(userInfoBean.getAvatar().getAvatarURL100());
                            user.setUser_pwd(MD5UT.create("123456"));
                            user.setGender(userInfoBean.getGender());
                            user.setUser_account("welphen_"+UuidUT.buildRandom(5));
                            user.setUser_status(1);
                            user.setFirst_ip(WebUT.ip());
                            user.setFirst_time(TimeHelper.getCurrentTime());
                            if(StringUtils.isBlank(commonService.addObject(user))){
                                throw new Exception("注册用户信息错误！");
                            }
                            bindTag = 2 ;
                        }
                        //存储用户信息
                        session.setAttribute(Constants.SESSION_HOME_USER, user);
                        session.setAttribute("bindTag", bindTag);
                    }
                }*/
            }else{
                log.info("请求非法");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:"+session.getAttribute("beforLoginUrl")+"";
    }


}
